import React from 'react';
import {injectIntl} from './intl';
import {Table} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {
    PAGE,
    TABLE,
    PAGINATION_OPTIONS,
    COMMON_TABLE_QUERY_FAIL_TEXT,
    COMMON_TABLE_EMPTY_TEXT,
    FIXED_COLUMN_WIDTH,
} from '../constants';
import {Link} from 'react-router-dom';
import {hasPermissions, conventSorter} from './utils';
import {baseDataStatus, currency} from '../Enum';
import {conventEnumValueToString, formatAmount} from '../utils';
import {PERMISSION} from './constants';
import DropdownMenu from 'Shared/components/DropdownMenu';
import WrappedPopconfirm from '../common/WrappedPopconfirm';

export class TablePanel extends React.PureComponent {
    state = {
        loading: false
    };
    handleAbandon = id => {
        this.setState({
            loading: true
        });
        this.props.onClickAbandon(id).then(() => {
            this.setState({
                loading: false
            });
        });
    };

    onChangeSort = (pagination, filters, sorter) => {
        if(pagination.current - 1 === this.props.pageIndex && pagination.pageSize === this.props.pageSize)
            this.props.onChangeSort({...conventSorter(sorter),
                pageIndex: PAGE.index});
    };
    render() {
        const columns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.brandCode',
                    defaultMessage: '品牌编号'
                }),
                dataIndex: 'brandCode',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.localCode',
                    defaultMessage: '地产件编号'
                }),
                dataIndex: 'localCode',
                render: (text, record) => (
                    <Link key="detail" to={routes.detail.format(record.id)}>
                        {text}
                    </Link>
                )
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.localName',
                    defaultMessage: '地产件名称'
                }),
                dataIndex: 'localName',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.minPackSize',
                    defaultMessage: '最小包装数'
                }),
                dataIndex: 'minPackSize',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.partReplacementCode',
                    defaultMessage: '替换件编号'
                }),
                dataIndex: 'partReplacementCode',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.currency',
                    defaultMessage: '币种'
                }),
                dataIndex: 'currency',
                render: text => conventEnumValueToString(currency, text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.price',
                    defaultMessage: '单价'
                }),
                dataIndex: 'price',
                render: text => formatAmount(text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.manufactory',
                    defaultMessage: '工厂'
                }),
                dataIndex: 'manufactory',
            },

            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.status',
                    defaultMessage: '状态'
                }),
                dataIndex: 'status',
                render: text => conventEnumValueToString(baseDataStatus, text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.action',
                    defaultMessage: '操作'
                }),
                dataIndex: 'action',
                width: FIXED_COLUMN_WIDTH,
                fixed: 'right',
                render: (t, r) => {
                    const menus = [
                        {
                            id: PERMISSION.abandon,
                            children: ref =>
                                <WrappedPopconfirm
                                    id={r.id}
                                    key="abandon"
                                    title={this.props.intl.formatMessage({
                                        id: 'tablePanel.popconfirm.message',
                                        defaultMessage: '是否继续?'
                                    })}
                                    onVisibleChange={ref.setMenuVisible}
                                    onConfirm={this.handleAbandon}>
                                    <a key="abandon">
                                        {this.props.intl.formatMessage({
                                            id: 'tablePanel.operation.abandon',
                                            defaultMessage: '作废'
                                        })}
                                    </a>
                                </WrappedPopconfirm>,
                            hidden: !(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(r.options, PERMISSION.abandon))
                        },
                    ];
                    return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
                }
            }
        ];
        if(!this.props.isDealerUser)
            columns.splice(1, 0, ...[
                {
                    title: this.props.intl.formatMessage({
                        id: 'tablePanel.column.dealerCode',
                        defaultMessage: '总代'
                    }),
                    dataIndex: 'dealerCode',
                    render: (text, record) => `(${record.dealerCode})${record.dealerName}`
                },
            ]);
        const pagination = {
            total: this.props.total,
            pageSize: this.props.pageSize,
            current: this.props.pageIndex + 1,
            onShowSizeChange: this.props.onPageSizeChange,
            onChange: this.props.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const locale = {
            emptyText: this.props.errorMessage ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        return (
            <div>
                <Table
                    className="white-space-nowrap"
                    columns={columns}
                    dataSource={this.props.data}
                    rowKey="id"
                    pagination={pagination}
                    loading={this.props.loading}
                    onChange={this.onChangeSort}
                    locale={locale}
                    {...TABLE}/>
            </div>
        );
    }
}
TablePanel.propTypes = {
    data: PropTypes.array.isRequired,
    errorMessage: PropTypes.string.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    onClickAbandon: PropTypes.func.isRequired,
    onPageIndexChange: PropTypes.func.isRequired,
    onPageSizeChange: PropTypes.func.isRequired,
    intl: PropTypes.object,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
};
import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {
    tableSearch,
    onClickAbandon,
} from './actions';
const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    data: getData(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    errorMessage: state.getIn(['page', 'domainData', 'list', 'message']),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    isDealerUser: state.getIn(['page', 'domainData', 'initData', 'isDealerUser']),
    permissions: getPermissions(state)
});

const mapDispatchToProps = dispatch => ({
    onPageSizeChange: (pageIndex, pageSize) =>
        dispatch(
            tableSearch({
                pageIndex: PAGE.index,
                pageSize
            })
        ),
    onPageIndexChange: pageIndex =>
        dispatch(
            tableSearch({
                pageIndex: pageIndex - 1
            })
        ),
    onChangeSort: option => dispatch(tableSearch(option)),
    onClickAbandon: id =>
        dispatch(onClickAbandon(id)).then(success => {
            if(success) dispatch(tableSearch({
                pageIndex: PAGE.index
            }));
            return success;
        }),
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(TablePanel));
